import 'package:flutter_admin/api/odoo/stock_move_line_odoo_api.dart';
import 'package:flutter_admin/models/user_info.dart';
import 'package:flutter_admin/pages/common/cry/cry.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/cry_dialog.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select_date.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/stock_materialcheck_odoo_api.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/stock_materialcheck.dart';
import 'package:flutter_admin/models/odoo/stock_materialcheckitem.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/odoo/stock_materialcheck/stock_materialcheck_edit.dart';
import 'package:flutter_admin/pages/odoo/stock_materialcheck/stock_materialcheck_dialog.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/pages/odoo/stock_materialcheck/stock_materialcheckitem/stock_materialcheckitem_inventory.dart';
import 'package:flutter_admin/pages/odoo/stock_materialcheck/stock_materialcheckitem/stock_materialcheckitem_list.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:intl/intl.dart';
import 'package:quiver/strings.dart';

class StockMaterialcheckList extends StatefulWidget {
  StockMaterialcheckList({Key? key}) : super(key: key);

  @override
  _StockMaterialcheckListState createState() => _StockMaterialcheckListState();
}

class _StockMaterialcheckListState extends State<StockMaterialcheckList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  StockMaterialcheck stockMaterialcheck = StockMaterialcheck();
  List<StockMaterialcheck> selectedList = [];
  List<SelectOptionVO> locationIdList = [];
  DateFormat format = DateFormat('yyyy-MM-dd');
  UserInfo userInfo = StoreUtil.getCurrentUserInfo();

  @override
  void initState() {
    super.initState();
    stockMaterialcheck.createDateStart = Utils.getDate();
    stockMaterialcheck.createDateEnd = Utils.getDate();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _loadSelectVO();
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  _loadSelectVO() async {
    if(isDisplayDesktop(context)){
      // if (userInfo.major != null) {
      //   locationIdList = await DynamicDataApi.getModelSelect(
      //       active: false,
      //       model: "stock.location",
      //       name: "complete_name",
      //       key: 'father_locaiton',
      //       val: null
      //   );
      // } else {
      //   locationIdList = await DynamicDataApi.getModelSelect(
      //       active: false,
      //       model: "stock.location",
      //       name: "complete_name",
      //       key: 'father_locaiton',
      //       val: null,
      //       key2: 'workshop_id',
      //       val2: int.parse(userInfo.deptId!));
      //   // stockMaterialcheck.workshopId = userInfo.deptId;
      // }
      locationIdList = await DynamicDataApi.getModelSelect(
          active: false,
          model: "stock.location",
          name: "complete_name",
          key: 'father_locaiton',
          val: null
      );
    }else{
      ResponseBodyApi res = await StockMoveLineOdooApi.getLocation(userInfo.userId);
      if (res.success!){
        for(var i = 0; i < res.data.length; i++){
          locationIdList.add(SelectOptionVO(value: res.data[i]["locaiton_id"].toString(),label: res.data[i]["locaiton_name"]));
        }
        if(res.data.length == 1){
          stockMaterialcheck.warehouseId = res.data[0]["location_id"].toString();
          _query();
        }
      }
    }
    setState(() {});
  }

  bool _checkStatus(List<StockMaterialcheck> selectedList) {
    for (var i = 0; i < selectedList.length; i++) {
      if (selectedList[i].isCheck == '1') return false;
    }
    return true;
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CrySelect(
            label: '盘点库房',
            width: 380,
            dataList: locationIdList,
            value: stockMaterialcheck.warehouseId,
            onSaved: (v) => {stockMaterialcheck.warehouseId = v},
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CrySelectDate(
            context,
            width: 180,
            label: '创建开始时间',
            value: stockMaterialcheck.createDateStart,
            lastDate: isNotBlank(stockMaterialcheck.createDateEnd)
                ? format.parse(stockMaterialcheck.createDateEnd!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              stockMaterialcheck.createDateStart = v;
              setState(() {});
            },
            onSaved: (v) {
              stockMaterialcheck.createDateStart = v;
            },
          ),
          CrySelectDate(
            context,
            width: 180,
            label: '创建结束时间',
            value: stockMaterialcheck.createDateEnd,
            firstDate: isNotBlank(stockMaterialcheck.createDateStart)
                ? format.parse(stockMaterialcheck.createDateStart!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              stockMaterialcheck.createDateEnd = v;
              setState(() {});
            },
            onSaved: (v) {
              stockMaterialcheck.createDateEnd = v;
            },
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('盘点计划')),
        DataColumn(label: Text('盘点库房')),
        DataColumn(label: Text('备注')),
        DataColumn(label: Text('盘点人')),
        DataColumn(label: Text('盘点时间')),
        DataColumn(label: Text('创建人')),
        DataColumn(label: Text('创建时间')),
      ],
      getCells: (m) {
        StockMaterialcheck stockMaterialcheck = StockMaterialcheck.fromMap(m);
        return [
          DataCell(Text(stockMaterialcheck.name ?? '--')),
          DataCell(Text(stockMaterialcheck.warehouseName ?? '--')),
          DataCell(Text(stockMaterialcheck.remark ?? '--')),
          DataCell(Text(stockMaterialcheck.inventoryName ?? '--')),
          DataCell(Text(stockMaterialcheck.inventoryTime ?? '')),
          DataCell(Text(stockMaterialcheck.createName ?? '--')),
          DataCell(Text(Utils.timeUTC(stockMaterialcheck.createDate ?? '--'))),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
        CryButtons.add(context, () => _edit(null)),
        CryButtons.edit(
            context,
            selectedList.length == 1 && selectedList[0].isCheck != '1'
                ? () => _edit(selectedList[0])
                : null),
        CryButtons.delete(
            context,
            selectedList.length != 0 && _checkStatus(selectedList)
                ? () => _delete(selectedList)
                : null),
        // CryButtons.edit(context, () => _edit(selectedList[0])),
        CryButton(
            label: '盘亏盘盈',
            iconData: Icons.view_headline,
            onPressed: selectedList.length == 1 && selectedList[0].isCheck == '1' && selectedList[0].isOver != '1'
                ? () => _profitLoss(selectedList[0])
                : null),
        CryButton(
            label: '查看明细',
            iconData: Icons.view_headline,
            onPressed: selectedList.length == 1 && selectedList[0].isOver == '1'
                ? () => _detailed(selectedList[0])
                : null),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          Wrap(
            children: [
              isDisplayDesktop(context) ? form : Container(),
              Padding(
                padding: EdgeInsets.only(top: 24),
                child: isDisplayDesktop(context) ? buttonBar : Container(),
              )
            ],
          ),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _edit(StockMaterialcheck? stockMaterialcheck) async {
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: StockMaterialcheckEdit(
          stockMaterialcheck: stockMaterialcheck,
        ),
      ),
    ).then((v) {
      if(v!= null){
        if(stockMaterialcheck == null){
          // 新增时回到第一页
          tableKey.currentState?.pageTo(0);
        }
        _loadData();
      }
    });

  }

  _delete(List<StockMaterialcheck> selectedList) async {
    cryConfirm(context, S.of(context).confirmDelete, (context) async {
      List ids = selectedList.map((v) {
        return int.parse(v.id!);
      }).toList();
      var result = await StockMaterialcheckOdooApi.removeByIds(ids);
      if (result.success!) {
        _query();
        CryUtils.message(S.of(Cry.context).success);
      }
    });
  }

  _profitLoss(StockMaterialcheck stockMaterialcheck) async {
    var res = await StockMaterialcheckOdooApi.profitLoss(stockMaterialcheck.id);
    if(res.success!){
      if(res.data == null){
        CryUtils.message("操作成功");
      }else{
        CryUtils.message(res.data);
      }
    }
  }

  _detailed(StockMaterialcheck stockMaterialcheck) {
    StockMaterialcheckitem stockMaterialcheckitem = StockMaterialcheckitem();
    stockMaterialcheckitem.checkId = stockMaterialcheck.id;
    Utils.fullscreenDialog(StockMaterialcheckitemList(
            stockMaterialcheckitem: stockMaterialcheckitem))
        .then((v) {
      if (v != null) {
        // _loadData();
      }
    });
  }

  _inventory(StockMaterialcheck stockMaterialcheck){
    StoreUtil.write("key", "stockMaterialcheckitemInventory");
    StockMaterialcheckitem stockMaterialcheckitem = StockMaterialcheckitem();
    stockMaterialcheckitem.checkId = stockMaterialcheck.id;
    stockMaterialcheckitem.locationId = stockMaterialcheck.warehouseId;
    Utils.fullscreenDialog(
        StockMaterialcheckitemInventory(stockMaterialcheckitem: stockMaterialcheckitem))
        .then((v) {
      if (v != null) {
        _loadData();
      }
    });
  }

  _reset() {
    stockMaterialcheck = StockMaterialcheck();
    formKey.currentState!.reset();
    stockMaterialcheck.createDateStart = Utils.getDate();
    stockMaterialcheck.createDateEnd = Utils.getDate();
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    if (isBlank(stockMaterialcheck.warehouseId)) {
      tableKey.currentState?.pageTo(0);
      tableKey.currentState?.loadData(PageModel());
      CryUtils.message("请选择库房位置");
      return;
    }
    ResponseBodyApi responseBodyApi = await StockMaterialcheckOdooApi.page(
        data: {"page": page, "domainList": stockMaterialcheck.toDomainList()});
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: StockMaterialcheckDialog(),
      ),
    ).then((v) {
      if (v != null) {
        stockMaterialcheck = v;
        _query();
      }
    });
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<StockMaterialcheck>((e) => StockMaterialcheck.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.add) {
          _edit(null);
        } else if (v == OperationType.edit) {
          _edit(selectedList[0]);
        } else if (v == OperationType.delete) {
          _delete(selectedList);
        } else if (v == OperationType.dmsFile) {
          _inventory(selectedList[0]);
        } else if (v == OperationType.print) {
          _profitLoss(selectedList[0]);
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.add,
          child: ListTile(
            leading: const Icon(Icons.add),
            title: Text('添加'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.edit,
          enabled: selectedList.length == 1 && selectedList[0].isCheck != '1',
          child: ListTile(
            leading: const Icon(Icons.edit),
            enabled: selectedList.length == 1 && selectedList[0].isCheck != '1',
            title: Text('修改'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.delete,
          enabled: selectedList.length != 0 && _checkStatus(selectedList),
          child: ListTile(
            leading: const Icon(Icons.delete), //Icons.delete
            enabled: selectedList.length != 0 && _checkStatus(selectedList),
            title: Text('删除'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.dmsFile,
          enabled: selectedList.length == 1 && selectedList[0].isCheck != '1',
          child: ListTile(
            leading: const Icon(Icons.attach_file_sharp), //Icons.delete
            enabled: selectedList.length == 1 && selectedList[0].isCheck != '1',
            title: Text('库存盘点'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.print,
          enabled: selectedList.length == 1 && selectedList[0].isCheck == '1' && selectedList[0].isOver != '1',
          child: ListTile(
            leading: const Icon(Icons.view_headline), //Icons.delete
            enabled: selectedList.length == 1 && selectedList[0].isCheck == '1' && selectedList[0].isOver != '1',
            title: Text('盘亏盘盈'),
          ),
        ),
      ],
    );
  }
}
